package org.example.myleet.p687;

import org.example.myleet.Utils.TreeNode;

public class Solution {

    private int maxLen;

    public int longestUnivaluePath(TreeNode root) {
        maxLen = 0;
        dfs(root);
        return maxLen;
    }

    private int dfs(TreeNode parent) {
        if (null == parent) {
            return 0;
        }
        int leftDepth = dfs(parent.left);
        int rightDepth = dfs(parent.right);
        int left1 = 0;
        if (null != parent.left && parent.val == parent.left.val) {
            left1 = leftDepth + 1;
        }
        int right1 = 0;
        if (null != parent.right && parent.val == parent.right.val) {
            right1 = rightDepth + 1;
        }
        maxLen = Math.max(maxLen, left1 + right1);
        return Math.max(left1, right1);
    }
}
